package com.mf.morefun.listener;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.mf.morefun.R;
import com.mf.morefun.util.TransformationUtils;
import com.mf.morefun.widget.GlideRoundTransform;
import com.zhcx.zhcxlibrary.utils.DeviceUtils;

public class MyRequestListener implements RequestListener {
    private ImageView ivPersonhead;
    private Context mContext;
    private int sizeW, sizeH;

    public MyRequestListener(ImageView ivPersonhead, Context mContext, int sizeW, int sizeH) {
        this.ivPersonhead = ivPersonhead;
        this.mContext = mContext;
        this.sizeW = sizeW;
        this.sizeH = sizeH;
    }

    @Override
    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
        Message msg = new Message();
        msg.what = 100;
        msg.obj = ivPersonhead;
        mHandler.sendMessage(msg);
        return false;
    }

    @Override
    public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
        return false;
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 100:
                    if (sizeW < DeviceUtils.dip2px(mContext, 100)){
                        CircleCrop circleCrop = new CircleCrop();
                        RequestOptions options = RequestOptions.bitmapTransform(circleCrop);
                        Glide.with(mContext).asBitmap().load(R.mipmap.ic_launcher).apply(options).into(new TransformationUtils((ImageView)msg.obj, mContext, sizeW, sizeH));
                    }else {
                        RequestOptions options = new RequestOptions().transform(new GlideRoundTransform(mContext, 14));
                        Glide.with(mContext).asBitmap().load(R.mipmap.ic_launcher).apply(options).into(new TransformationUtils((ImageView)msg.obj, mContext, sizeW, sizeH));
                    }
                    break;
            }
        }
    };

}
